//
//  ByInteractiveController.m
//  beibei_ios
//
//  Created by pro on 16/4/21.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByInteractiveController.h"

@interface ByInteractiveController ()

@property (nonatomic, assign) BOOL shouldComplete;
@property (nonatomic, strong) UIViewController *presentingVC;

@end

@implementation ByInteractiveController

-(void)wireToViewController:(UIViewController *)viewController {

    self.presentingVC = viewController;
    [self prepareGestureRecognizerInView:viewController.view];
}

- (void)prepareGestureRecognizerInView:(UIView*)view {
    
    // 边缘滑动手势
    UIScreenEdgePanGestureRecognizer *edgePanGestureRecognizer = [[UIScreenEdgePanGestureRecognizer alloc]initWithTarget:self action:@selector(handleGesture:)];
    // 设置从左边边界滑入
    edgePanGestureRecognizer.edges = UIRectEdgeLeft;
    [view addGestureRecognizer:edgePanGestureRecognizer];

}

- (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer {
    
    // 计算手指滑的物理距离（滑了多远，与起始位置无关）
    CGFloat progress = [gestureRecognizer translationInView:self.presentingVC.view].x / self.presentingVC.view.width;
    progress = MIN(1.0, MAX(0.0, progress)); // 把这个百分比限制在0~1之间

    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            
            self.interacting = YES;

            [self.presentingVC.navigationController popViewControllerAnimated:YES];
            break;
        case UIGestureRecognizerStateChanged: {

            self.shouldComplete = (progress > 0.5);

            // 当手慢慢划入时，我们把总体手势划入的进度告诉 UIPercentDrivenInteractiveTransition 对象。
            [self updateInteractiveTransition:progress];
            
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled: {

            self.interacting = NO;
            if (!self.shouldComplete || gestureRecognizer.state == UIGestureRecognizerStateCancelled) {
                [self cancelInteractiveTransition];
            } else {
                [self finishInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}


@end
